/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.example.echo;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Handler implementation for the echo server.
 * echo server,服务端实现
 *
 * @Sharable,表示该类可以重用
 */
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 每当有消息时,都会执行此方法
     * 一个缓冲区内可能会有很多数据,
     * 不一定一次全部发送,可能分批次发送.
     * 但最后一定会发送完成.
     * 数据按顺序发送.
     *
     * 所以,这里拿到的数据,不一定是全部数据
     * @param ctx
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("channelRead : write : "+msg.toString());
        //读取的消息,写入缓存区
        ctx.write(msg);
        System.out.println("channelRead end : write : "+msg.toString());
    }

    /**
     * read完成后的动作.
     * 当一次发送完成的数据全部读取完成后,触发此动作
     * @param ctx
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        System.out.println("channelReadComplete : flush");
        //数据读取完毕, 刷新缓存区,将数据写入到pipline
        ctx.flush();
        System.out.println("channelReadComplete end : flush");
    }

    /**
     * 每当有异常时,触发此动作
     * 异常包含所有流程中的异常
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        //打印出异常栈
        cause.printStackTrace(System.out);
        //关闭链接
        ctx.close();
    }
}
